# encoding:utf-8
# http://www.360doc.com/content/17/0624/12/1489589_666148811.shtml
# import theano
import datetime
import os
import pandas as pd
import numpy
import math
from keras.models import load_model
from matplotlib.axes import Axes
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

os.environ['CUDA_VISIBLE_DEVICES'] = "0"
from keras.datasets import mnist
from matplotlib import pyplot as plt

(X_train, y_train), (X_test, y_test) = mnist.load_data()
print(X_train.shape)

plt.imshow(X_train[0])  # 显示图像
plt.show()
# plt.close()




# ==================================================================================

dataframe = pd.read_csv('data/international-airline-passengers.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
dataset = dataset.astype('float32')


def create_dataset(dataset, look_back=1):
    """
    :param dataset: numpy.ndarray
    :param look_back: int
    :return:
    """
    # print(type(dataset))
    # print(dataset)
    # exit(0)
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        dataX.append(a)
        dataY.append(dataset[i + look_back, 0])
    return numpy.array(dataX), numpy.array(dataY)


# fix random seed for reproducibility
numpy.random.seed(7)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.67)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
# use this function to prepare the train and test datasets for modeling
look_back = 2
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# reshape input to be [samples, time steps, features]
trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# ============================================================================================





model = load_model('output/lstm_timeseries_model.hdf5')
# make predictions
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

# invert predictions
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])

trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % trainScore)
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % testScore)

# shift train predictions for plotting
trainPredictPlot = numpy.empty_like(dataset)
trainPredictPlot[:, :] = numpy.nan
trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict

# shift test predictions for plotting
testPredictPlot = numpy.empty_like(dataset)
testPredictPlot[:, :] = numpy.nan
testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict

# plot baseline and predictions
# 画出结果：蓝色为原数据，绿色为训练集的预测值，红色为测试集的预测值
f, (ax1, ax2) = plt.subplots(figsize=(10, 8), nrows=2)
# print(scaler.inverse_transform(dataset))
# print(dataset)
# exit(0)
assert isinstance(ax1, Axes)
df = pd.read_csv('data/international-airline-passengers.csv')
df.columns = ['ds', 'y']
x_axis1 = list(map(lambda x: datetime.datetime.strptime(x, '%Y-%m'), df['ds'].values.tolist()))
df['ds'] = x_axis1
x_axis = x_axis1[0:141]
# print(x_axis)

ax1.plot(x_axis, scaler.inverse_transform(dataset))
ax1.plot(x_axis, trainPredictPlot)
# print(trainPredictPlot)
# exit(0)
ax1.plot(x_axis, testPredictPlot)

# ax1.show()










# plt.close()

df = df.head(int(df['ds'].count()*0.67))
from fbprophet import Prophet
m = Prophet(growth='logistic')
df['cap'] = 800
m.fit(df)
future = m.make_future_dataframe(periods=48, freq='M')
future['cap'] = 800
# future.tail()
forecast = m.predict(future)
# forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail()
m.plot(forecast, ax=ax2).show()
# m.plot_components(forecast).show()
fb_predict_index = forecast['ds'].copy().values

# print(fb_predict_index)
# exit(0)
# fb_predict_index = list(map(lambda x: datetime.datetime.fromtimestamp(-x / 1000000000), fb_predict_index))
# print(fb_predict_index)
# exit(0)
fb_predict_y = forecast['yhat'].values
print(fb_predict_y)
print(len(fb_predict_index), len(fb_predict_y))

ax1.plot(fb_predict_index, fb_predict_y)

min_date = datetime.datetime.now().replace(1948, 1, 1)
max_date = datetime.datetime.now().replace(1962, 1, 1)
ax1.set(xlim=[min_date, max_date])
ax2.set(xlim=[min_date, max_date])



plt.show()
